/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun<lingyun@email.com>
 *                  All rights reserved.
 *
 *       Filename:  socket_sever.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(13/03/25)
 *         Author:  LingYun <lingyun@email.com>
 *      ChangeLog:  1, Release initial version on "13/03/25 16:06:50"
 *                 
 ********************************************************************************/
#include "socket_server.h"

int socket_server(char *listen_ip,int listen_port)
{
	int                       sockfd;
    int                       on=1;
	struct  sockaddr_in       servaddr;
	int                       rv=0;

	sockfd=socket(AF_INET,SOCK_STREAM,0);
	if(sockfd<0)
	{
		dbg_print("Creat socket failure: %s\n",strerror(errno));
		return -1;
	}
	dbg_print("Create socket[%d] successfully!\n",sockfd);
	setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));

	memset(&servaddr,0,sizeof(servaddr));
	servaddr.sin_family=AF_INET;
	servaddr.sin_port=htons(listen_port);

	if(!listen_ip)   /*没有传IP*/
	{
		servaddr.sin_addr.s_addr=htonl(INADDR_ANY);    /*服务器会监听所有可用网络接口(INADDR_ANY)*/
	}
	else     /*传了IP*/
	{
		if(inet_pton(AF_INET,listen_ip,&servaddr.sin_addr) <= 0)  /*把传进来的IP地址十进制转成二进制，*/
		{
			dbg_print("inet_pton() set listen IP address failure\n");
			rv=-2;
			goto CleanUp;
		}
	}

	if((rv = bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))) < 0)
	{
		dbg_print("Socket[%d] bind on port[%d] failure:%s\n", sockfd, listen_port, strerror(errno));
		rv=-3;
		goto CleanUp;
	}

	if(listen(sockfd,128)<0)
	{
		dbg_print("listen port failure:%s\n",strerror(errno));
		rv=-4;
		goto CleanUp;
	}


	CleanUp:
		if(rv<0)
			close(sockfd);
		else
			rv = sockfd;

	return rv;

}


void socket_rlimit(void)
{
	struct rlimit limit = {0};
	getrlimit(RLIMIT_NOFILE, &limit );
	limit.rlim_cur = limit.rlim_max;
	setrlimit(RLIMIT_NOFILE, &limit );
	dbg_print("Set socket open fd max count to %ld\n", limit.rlim_max);
}

